#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <semaphore.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>

struct Job
{
    void (*task)(void *arg); // 指向线程需要执行的具体任务
    void *arg;               // 线程传的参数

    struct Job *next;
};

struct thread_pool
{
    int thread_num;     // 线程池的线程数量
    int queue_max_size; // 任务队列的最大值
    int queue_cur_size; // 任务队列的当前任务的个数

    pthread_t *ids;                 // 保存线程池中线程的id
    pthread_mutex_t mutex;          // 线程池的锁
    pthread_cond_t empty_queue;     // 等待任务队列空的条件
    pthread_cond_t not_empty_queue; // 等待任务队列非空
    pthread_cond_t not_full_queue;  // 等待任务队列非满队

    struct Job *font;
    struct Job *real;

    int pool_close;  // 线程池关闭：0  线程池运行：1
    int queue_close; // 任务队列是否可以操作的标志位；
};
struct thread_pool *Create_pool(int thread_num, int queue_max_size)
{
    struct thread_pool *pool = (struct thread_pool *)malloc(sizeof(struct thread_pool));
    if (pool == NULL)
    {
        printf("pool malloc is error!\n");
        return NULL;
    }

    pool->thread_num = thread_num;
    pool->queue_max_size = queue_max_size;
    pool->queue_cur_size = 0;

    if (pthread_mutex_init(&(pool->mutex), NULL) != 0)
    {
        perror("thread pool mutex init error!");
        goto err;
    }

    if (pthread_cond_init(&(pool->not_empty_queue), NULL) != 0)
    {
        perror("thread pool cond not empty queue init error!");
        goto err;
    }

    if (pthread_cond_init(&(pool->not_full_queue), NULL) != 0)
    {
        perror("thread pool cond not full queue init error!");
        goto err;
    }

    if (pthread_cond_init(&(pool->empty_queue), NULL) != 0)
    {
        perror("thread pool cond empty queue init error!");
        goto err;
    }

    pool->font = NULL;
    pool->real = NULL;

    pool->queue_close = 0;
    pool->pool_close = 0;

    pool->ids = (pthread_t *)malloc(sizeof(pthread_t) * thread_num);
    if (pool->ids == NULL)
    {
        printf("pthread ids malloc error!\n");
        goto err;
    }
    memset(pool->ids, 0, sizeof(pthread_t) * thread_num);

    for (int i = 0; i < thread_num; i++)
    {
        if (pthread_create(&(pool->ids[i]), NULL, thread_function, (void *)pool) < 0)
        {
            perror("thread create error!");
            goto err;
        }
    }

    return pool;
err:
    free(pool);
    pool = NULL;
    return pool;
}
void thread_function(void *arg)
{
    struct thread_pool *pool = (struct thread_pool *)arg;
    pthread_mutex_lock(&pool->mutex);
    while (1)
    {
        if (pool->queue_close == 0 || pool->pool_close == 0)
        {
            printf("queue empty\n");
            pthread_mutex_lock(&pool->mutex);
            pthread_exit(NULL);
        }
        while ((pool->queue_cur_size == 0) && (pool->queue_close != 1))
        {
            pthread_cond_wait(&(pool->not_empty_queue), &(pool->mutex));
        }
        // 从任务队列中取任务;
        struct Job *job = pool->font;
        pool->font = pool->font->next;
        pool->queue_cur_size--;
        if(pool->queue_cur_size==0)
        {
            pthread_cond_broadcast(&pool->empty_queue);
            
        }
    }
}


int create_tcp_server_socket(char *ip, int port)
{
    signal(SIGPIPE, SIG_IGN);

    int sockfd;
    int sockaddr_len;

    struct in_addr server_ip;
    struct sockaddr_in server_addr;
    // 1、socket函数创建套接字 -->  文件描述符
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket create failed!\n");
        exit(1);
    }
    printf("socket create Success! %d\n", sockfd);

    int reuse = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    //??为什么要绑定IP和端口号？接受客户端的连接，就需要确定服务器的IP和端口号
    // 2、bind：给套接字绑定IP地址和端口号
    // 初始化struct sockadd_in变量；

    inet_pton(AF_INET, ip, (void *)&server_ip);
    server_addr.sin_family = AF_INET;   // IPV4
    server_addr.sin_addr = server_ip;   // IP
    server_addr.sin_port = htons(port); // h:host to n:net

    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0)
    {
        perror("bind ip & port failed!");
        exit(1);
    }
    printf("bind Success ip = %s port = %d\n", ip, port);

    // 3、listen：监听：允许其他人进行连接请求
    if (listen(sockfd, 20) < 0)
    {
        perror("listen failed!\n");
        exit(1);
    }
    printf("listen Success!\n");

    return sockfd;
}

void setnonblock(int sockfd)
{
    int flags = fcntl(sockfd, F_GETFL);
    flags = flags | O_NONBLOCK;
    fcntl(sockfd, F_SETFL, flags);
}

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        printf("Please input server bind ip and port!\n");
        exit(1);
    }

    int sockfd;
    int r_len;
    int confd;
    int tempfd;
    int sockaddr_len;
    char message[1024] = {0};
    char client_ip[INET_ADDRSTRLEN];
    struct sockaddr_in client_addr;

    int client_fds[1024];
    for (int i = 0; i < 1024; i++)
    {
        client_fds[i] = -1;
    }

    sockfd = create_tcp_server_socket(argv[1], atoi(argv[2]));

    setnonblock(sockfd);

    // 4、accept: 处理连接请求：三次握手
    while (1)
    {
        sockaddr_len = sizeof(struct sockaddr);
        // confd:连接描述符（文件描述符） 每成功连接一个客户端，对应生成唯一的连接描述符
        confd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t *)&sockaddr_len);
        if (confd < 0)
        {
            if (errno != EAGAIN)
            {
                perror("accept failed!");
                exit(1);
            }
        }
        else
        {
            inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
            printf("client ip = %s port = %d\n", client_ip, client_addr.sin_port);
            printf("confd = %d\n", confd);
            setnonblock(confd);
            for (int i = 0; i < 1024; i++)
            {
                if (client_fds[i] == -1)
                {
                    client_fds[i] = confd;
                    break;
                }
            }
        }

        for (int i = 0; i < 1024; i++)
        {
            if (client_fds[i] != -1)
            {
                tempfd = client_fds[i];
                r_len = read(tempfd, message, sizeof(message));
                if (r_len < 0)
                {
                    if (errno != EAGAIN)
                    {
                        perror("read client message error!");
                        exit(1);
                    }
                }
                else if (r_len == 0)
                {
                    printf("client is close!\n");
                    client_fds[i] = -1;
                    shutdown(tempfd, SHUT_RDWR);
                }
                else if(r_len > 0)
                {
                    message[r_len] = '\0';
                    printf("recv client msg: %s\n", message);
                    //send(tempfd, "OK\n", 3, 0); // 如果confd已经断开（关闭),如果继续发送，产生一个SIGPIPE，终止当前进程
                    write(tempfd, "OK\n", 3);
                }
               
            }
        }

        // 5、send/recv: 收发数据
        // r_len = recv(confd, message, sizeof(message), 0);

        // close(sockfd); //关闭服务器
    }

    // 6、close/shutdown： 关闭连接

    return 0;
}